/**
 * 
 */
package com.csc.bankingsystem.core.dao.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import org.springframework.stereotype.Repository;

import com.csc.bankingsystem.core.dao.TransferRecordDAO;
import com.csc.bankingsystem.core.dto.BSPaging;
import com.csc.bankingsystem.core.entity.HistoryRecord;
import com.csc.bankingsystem.core.entity.TransferRecord;
import com.csc.bankingsystem.core.entity.UserInfo;

/**
 * Define all Data access operations of TransferRecordDAO
 * 
 * @author angelkidid
 *
 */
@Repository("transferRecordDAO")
public class TransferRecordDAOImpl extends GenericDAOImpl<TransferRecord> implements
		TransferRecordDAO {

	public List<TransferRecord> findByUserInfo(BSPaging paging, UserInfo userInfo, Date toDate) {
		Criteria criteria = getSession().createCriteria(TransferRecord.class);
		
//		criteria.add(Restrictions.eq("historyRecord.userInfo", userInfo));
		if(toDate != null){
			criteria.add(Restrictions.le("transDate", toDate));
		}
		
		DetachedCriteria subquery = DetachedCriteria.forClass(HistoryRecord.class)
			    .add(Restrictions.eq("userInfo.id", userInfo.getId()))
			    .setProjection(Projections.property("id"));
		
		criteria.add(Subqueries.propertyIn("historyRecord.id", subquery));
		
		criteria.addOrder(Order.desc("transDate"));
		criteria.setFirstResult(paging.getFirstResult());
		criteria.setMaxResults(paging.getPageSize());
		@SuppressWarnings("unchecked")
		List<TransferRecord> result = criteria.list();
		return CollectionUtils.isEmpty(result)?null:result;
	}
}
